<template>
  <div class="nursing-record-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-input
          placeholder="请输入客户ID"
          style="width: 200px"
          v-model="queryCustomerId"
          class="search-input"
      ></el-input>
      <el-button
          @click="queryByCustomerId"
          type="success"
          plain
          class="search-button"
      >
        查询
      </el-button>
      <el-button
          @click="showAddRecordDialog"
          type="primary"
          class="register-button"
      >
        新增护理记录
      </el-button>
    </div>

    <!-- 错误信息 -->
    <div class="error-message">{{ errorMessage }}</div>

    <!-- 护理记录表格 -->
    <el-table
        :data="nursingRecordList"
        class="customer-table"
        header-cell-class-name="table-header"
    >
      <el-table-column
          label="序号"
          type="index"
          width="60px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customerId"
          label="客户ID"
          width="100px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="itemId"
          label="护理项目ID"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="nursingTime"
          label="护理时间"
          width="150px"
          align="center"
          :formatter="formatDate"
      ></el-table-column>
      <el-table-column
          prop="nursingContent"
          label="护理内容"
          width="200px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="nursingCount"
          label="护理数量"
          width="80px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="userId"
          label="护理人员ID"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column label="操作" width="160px" align="center">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="showEditDialog(scope.row.id)"
              class="edit-button"
          >
            修改
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="removeOne(scope.row.id)"
              class="delete-button"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
      />
    </div>

    <!-- 护理记录对话框 -->
    <el-dialog
        v-model="nursingRecordDialog"
        :title="dialogTitle"
        class="customer-dialog"
    >
      <el-form :model="curNursingRecord" class="customer-form" :rules="recordRules" ref="recordForm">
        <el-form-item label="客户ID" prop="customerId" required>
          <el-col :span="22">
            <el-input v-model.number="curNursingRecord.customerId" class="form-input" ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="护理项目ID" prop="itemId" required>
          <el-col :span="22">
            <el-input v-model.number="curNursingRecord.itemId" class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="护理时间" prop="nursingTime" required>
          <el-col :span="22">
            <el-date-picker
                v-model="curNursingRecord.nursingTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择护理时间"
                class="form-input"
            ></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="护理内容" prop="nursingContent" required>
          <el-col :span="22">
            <el-input
                type="textarea"
                v-model="curNursingRecord.nursingContent"
                rows="3"
                class="form-input"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="护理数量" prop="nursingCount" required>
          <el-col :span="22">
            <el-input v-model.number="curNursingRecord.nursingCount" class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="护理人员ID" prop="userId" required>
          <el-col :span="22">
            <el-input v-model.number="curNursingRecord.userId" class="form-input"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="nursingRecordDialog = false">取消</el-button>
        <!-- 根据dialogTitle判断显示哪个按钮 -->
        <el-button
            v-if="dialogTitle === '新增护理记录'"
            type="primary"
            @click="handleAddRecordSubmit"
        >
          新增
        </el-button>
        <el-button
            v-if="dialogTitle === '护理记录信息修改'"
            type="primary"
            @click="handleEditRecordSubmit"
        >
          修改
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import http from '@/axios/http';
import qs from "qs";
import { ElMessage } from 'element-plus';

// 护理记录列表
const nursingRecordList = ref([]);
// 错误提示
const errorMessage = ref("");
// 查询条件 - 客户ID
const queryCustomerId = ref("");
// 对话框显示控制
const nursingRecordDialog = ref(false);
// 当前编辑的护理记录
const curNursingRecord = ref({});
// 对话框标题
let dialogTitle = ref('');
// 分页相关
const pageContains = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 表单验证规则
const recordRules = reactive({
  customerId: [{ required: true, message: '请选择客户', trigger: 'blur' }],
  itemId: [{ required: true, message: '请输入护理项目ID', trigger: 'blur' }],
  nursingTime: [{ required: true, message: '请选择护理时间', trigger: 'change' }],
  nursingContent: [{ required: true, message: '请输入护理内容', trigger: 'blur' }],
  nursingCount: [{ required: true, message: '请输入护理数量', trigger: 'blur' }],
  userId: [{ required: true, message: '请输入护理人员ID', trigger: 'blur' }]
});

// 页面初始化加载护理记录列表
onMounted(() => {
  getAllNursingRecords();
});

// 获取所有护理记录信息
function getAllNursingRecords() {
  let params = {
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
    customerId: queryCustomerId.value
  };
  http.post('/lyy/get_all_nurserecords', qs.stringify(params))
      .then((res) => {
        let result = res.data;
        if (result.result === 'success') {
          console.log('后端返回数据:', result.data.list);
          pageContains.value = result.data;
          nursingRecordList.value = result.data.list;
          console.log('赋值后 nursingRecordList:', nursingRecordList.value);
        } else {
          errorMessage.value = result.error;
        }
      });
}
// 根据客户ID查询护理记录
function queryByCustomerId() {
  pageContains.value.pageNum = 1;
  getAllNursingRecords();
}

// 显示添加对话框
function showAddRecordDialog() {
  nursingRecordDialog.value = true;
  dialogTitle = "新增护理记录";
  curNursingRecord.value = {
    customerId: null,
    itemId: null,
    nursingTime: new Date(),
    nursingContent: '',
    nursingCount: 1,
    userId: null
  };
  console.log('打开新增对话框');
}

// 显示编辑对话框
function showEditDialog(id) {
  getNursingRecordInfo(id);
  nursingRecordDialog.value = true;
  dialogTitle = "护理记录信息修改";
  console.log('打开修改对话框');
}

function getNursingRecordInfo(id) {
  let param = { id: id };
  http.post('/lyy/get_nurserecord_by_id', qs.stringify(param))
      .then((res) => {
        let result = res.data;
        if (result.result === 'success') {
          curNursingRecord.value = result.data;
        } else {
          errorMessage.value = result.error;
        }
      })
      .catch((error) => {
        console.error('获取护理记录信息出错:', error);
        errorMessage.value = '网络请求出错，请稍后重试';
      });
}

// 删除护理记录
function removeOne(id) {
  let param = { id: id };
  http.post('/lyy/remove_nurserecord_by_id', qs.stringify(param))
      .then((res) => {
        let result = res.data;
        if (result.result === 'success') {
          getAllNursingRecords();
        } else {
          errorMessage.value = result.error;
        }
      })
      .catch((error) => {
        console.error('删除护理记录出错:', error);
        errorMessage.value = '网络请求出错，请稍后重试';
      });
}

// 提交新增记录
function handleAddRecordSubmit() {
  const apiUrl = '/lyy/add_nurserecord';
  console.log('即将发送的新增数据:', curNursingRecord.value);
  http.post(apiUrl, curNursingRecord.value).then(res => {
    if (res.data.result ==='success') {
      nursingRecordDialog.value = false;
      getAllNursingRecords();
      ElMessage.success('新增成功');
    } else {
      errorMessage.value = res.data.error;
      ElMessage.error('操作失败，请重试');
    }
  });
}

// 提交修改记录
function handleEditRecordSubmit() {
  const apiUrl = '/lyy/update_nurserecord';
  console.log('即将发送的修改数据:', curNursingRecord.value);
  http.post(apiUrl, curNursingRecord.value).then(res => {
    if (res.data.result ==='success') {
      nursingRecordDialog.value = false;
      getAllNursingRecords();
      ElMessage.success('修改成功');
    } else {
      errorMessage.value = res.data.error;
      ElMessage.error('操作失败，请重试');
    }
  });
}

// 格式化日期
function formatDate(row, column) {
  let data = row[column.property];
  if (data == null) {
    return null;
  }
  let dt = new Date(data);
  return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
}

// 分页处理
const handlePageChange = (pageNum1) => {
  pageContains.value.pageNum = pageNum1;
  getAllNursingRecords();
};

const handleSizeChange = (pageSize1) => {
  pageContains.value.pageSize = pageSize1;
  getAllNursingRecords();
};
</script>

<style scoped>
.nursing-record-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.search-button {
  margin-right: 20px;
}

.register-button {
  width: 120px;
  font-weight: bold;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

.customer-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-header {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  width: 100%;
}

.customer-dialog {
  width: 500px;
}

.customer-form {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-input,
.form-select {
  width: 100%;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-button {
  width: 100%;
  padding: 10px;
}

.edit-button {
  margin-right: 10px;
}

.delete-button {
  margin-right: 10px;
}
</style>